package com.open.capacity.common;


import com.open.capacity.common.config.ServerConfig;
import com.open.capacity.prints.util.FileUtil;
import com.open.capacity.prints.util.uuid.UUIDUtils;
import com.open.capacity.utils.DateUtil;
import com.open.capacity.utils.file.FileUploadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Base64;

@Slf4j
@Service
public class FileService {

    @Autowired
    private ServerConfig serverConfig;

    @Value("${file.uploadpath:/usr/local/files/upload}")
    private String fileuploadPath;

    public String upload(MultipartFile file) throws IOException {
        // 上传文件路径
        String filePath = fileuploadPath + "/upload";
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        String url = serverConfig.getUrl() + fileName;
        return url;

    }

    public String uploadBase64(String base64Str) throws IOException {
        // 上传文件路径
        String filePath = fileuploadPath + "/upload";
        String fileName = DateUtil.dateNow() + "/" + FileUploadUtils.encodingFilename(UUIDUtils.getOriginalUUIDWithoutBar().replaceAll("-", "")) + "." + "jpg";
        File file = new File(filePath, fileName);
        byte[] fileBytes = Base64.getDecoder().decode(base64Str);
        org.apache.commons.io.FileUtils.writeByteArrayToFile(file, fileBytes);
        String pathFileName = FileUploadUtils.getPathFileName(filePath, fileName);
        String url = serverConfig.getUrl() + pathFileName;
        return url;
    }

    public String upload(File file) throws Exception {
        // 上传文件路径
        String filePath = fileuploadPath + "/upload";
        MultipartFile multipartFile = FileUtil.toMultipartFile("file", file);

        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, multipartFile);
        String url = serverConfig.getUrl() + fileName;
        return url;

    }
}
